<template>
  <div>
    <el-container>
      <el-header
        style="display:flex;align-items: center;justify-content: space-between;padding: 10px;border-bottom: 1px solid #f2f2f2;"
      >
        <div>
          <svg-icon class="primary" :icon-class="$route.meta.icon" />
          <span class="primary">{{companyForm.name}}员工导入</span>
        </div>
      </el-header>
      <div class="pd10">
        <div style="align-items: center;margin: 10px; margin-left: 20px">
          <el-row :gutter="24" style="margin-bottom: 10px">
            <div style="line-height:1.8;font-size:20px">上传员工变动名单</div>
            <div style="line-height:1.5;font-size:16px">员工变动名单说明</div>
            <div style="line-height:1.2;font-size:14px">1.若企业提供多个变动名单，可分批上传与提交；</div>
            <div style="line-height:1.2;font-size:14px">2.若手动为企业填写员工变动名单，请点击下载模板</div>
            <div style="line-height:1.2;font-size:14px">3.提交变动名单不可撤回，需要通过数据覆盖进行修改</div>
          </el-row>
          <el-row :gutter="24" style="margin-bottom: 10px">
            <ExportList2Excel ref="exportList2Excel" @handleExport="handleExport" name="下载模板" />
            <el-popover
              placement="bottom"
              title="温馨提示"
              width="200"
              trigger="manual"
              :content="popoverContent"
              v-model="popoverVisible"
            >
              <el-button
                style="margin-left: 10px"
                icon="el-icon-refresh-right"
                type="info"
                @click="daoruClick"
                slot="reference"
              >上传员工表格</el-button>
            </el-popover>
          </el-row>
        </div>
        <el-table :data="memberData" border stripe ref="table" style="width: 100%;">
          <el-table-column label="企业id" align="center" prop="companyId" width="100"></el-table-column>
          <el-table-column label="企业名称" align="center" prop="companyName"></el-table-column>
          <el-table-column label="手机号码" align="center" prop="mobile" width="120"></el-table-column>
          <el-table-column label="用户名称" align="center" prop="name" width="100"></el-table-column>
          <el-table-column label="vip等级" align="center" prop="vip" width="100"></el-table-column>
          <el-table-column label="错误提示" align="center" prop="errorMsg"></el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <el-row :gutter="24" style="margin-bottom: 10px">
          <el-button
            style="margin-left: 10px"
            icon="el-icon-refresh-right"
            type="info"
            :loading="checked"
            @click="updateClick"
          >确认上传</el-button>
        </el-row>
      </el-footer>
      <upload-excel-component
        ref="upload"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
      />

      <el-dialog
            title="提示"
            :visible.sync="centerDialogVisible"
            width="30%"
            center>
            <p><b id="DialogMsg" >{{companyForm.name}}</b>，增加总人数： <b id="DialogMsg">{{dialogNum}}</b>人，信息确认完成，请点击下方的确认上传</p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </el-container>
  </div>
</template>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list, del, update } from "@/api/member";
import { upload } from "@/api/companyEmployee";
import { find } from "@/api/company";
import utils from "../../utils/utils.js";
import { EventBus } from "@/api/eventBus";
import Pagination from "@/components/Pagination";
import CategoryPanel from "@/components/CategoryPanel";
import UploadExcelComponent from "@/components/UploadExcel/index.vue";
import ExportList2Excel from "@/components/ExportList2Excel";

export default {
  name: "employee-list",
  directives: { permission },
  data() {
    return {
      memberData: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      query: {
        name: "",
        phone: "",
        vip: ""
      },
      keyword: {
        name: "",
        phone: ""
      },
      queryPhone: "",
      queryName: "",
      curHeight: null,
      excelData: [],
      memberCategoryId: "",
      deleted: false,
      restoreForm: {
        id: "",
        deleted: false
      },
      companyForm: {
        id: "",
        name: ""
      },
      daoruData: "",
      daoruType: false,
      firstSheetName: "",
      checked: false, //防止双击
      checkTableDataLock: false, //表格数据检验的锁，前端检验成功后解锁
      popoverVisible: false, //导入检验成功后的弹窗提示
      popoverContent: "", //弹窗提示的内容
      centerDialogVisible:false,
      dialogNum:0
    };
  },
  components: {
    Pagination,
    CategoryPanel,
    UploadExcelComponent,
    ExportList2Excel
  },
  created() {
    var _this = this;
    _this.companyId = this.$route.query.companyId;
    _this.companyForm.id = this.$route.query.companyId;
    _this.companyForm.name = this.$route.query.companyName;
    console.info("_this.companyId--" + _this.companyId);
    // this.loadMember(_this.companyId)
    EventBus.$on("employee-add", res => {
      // 监听新增完毕
      // 更新列表数组
      _this.memberData.splice(0, 0, res);
    });
    EventBus.$on("employee-edit", res => {
      // 监听新增完毕
      // 更新列表数组
      for (var i = 0; i < _this.memberData.length; i++) {
        if (_this.memberData[i].id == res.id) {
          _this.memberData[i] = res;
        }
      }
    });
  },
  mounted() {
    this.comeIn();
    this.beforeMount();
  },
  methods: {
    watchGender(val) {
      if (val == "男") {
        return 1;
      } else if (val == "女") {
        return 2;
      } else {
        return "隐藏";
      }
    },

    watchVip(val) {
      if (val == "vip0") {
        return 0;
      } else if (val == "vip1") {
        return 1;
      } else if (val == "vip2") {
        return 2;
      } else if (val == "vip3") {
        return 3;
      } else if (val == "vip4") {
        return 4;
      } else if (val == "vip5") {
        return 5;
      } else {
        return -1;
      }
    },

    matchVip(val) {
      if (val == 0) {
        return "vip0";
      } else if (val == 1) {
        return "vip1";
      } else if (val == 2) {
        return "vip2";
      } else if (val == 3) {
        return "vip3";
      } else if (val == 4) {
        return "vip4";
      } else if (val == 5) {
        return "vip5";
      }
    },

    //下载模板的函数
    handleExport() {
      var _this = this;
      //要导出函数携带的参数
      let data = {};
      console.log("下载模板的函数this.companyForm.name--" + JSON.stringify(this.companyForm.name));
      data.tHeader = ["企业ID", "企业名称", "手机号码", "用户名称", "vip等级"];
      data.filterVal = ["companyId", "companyName", "mobile", "name", "vip"];
      data.filename = this.companyForm.name + "名单导入模板";
      data.list = [
        {
          companyId: this.companyForm.id,
          companyName: this.companyForm.name,
          mobile: 18888888888,
          name: "张三",
          vip: "vip1"
        }
      ];
      _this.$refs.exportList2Excel.handleDownload(data);
    },

    //名单导入
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        return true;
      }
      this.$message({
        message: "Please do not upload files larger than 1m in size.",
        type: "warning"
      });
      return false;
    },

    //导入表单成功回调事件
    handleSuccess({ results, header, firstSheetName }) {
      let _this = this;
      let matchInfo = [
        { label: "企业ID", value: "companyId" },
        { label: "企业名称", value: "companyName" },
        { label: "手机号码", value: "mobile" },
        { label: "用户名称", value: "name" },
        { label: "vip等级", value: "vip" }
      ];
      _this.memberData = [];
      console.log("获取的导入结果_this.memberData--" + JSON.stringify(_this.memberData));
      let matchResults = [];
      let origenalResult = [];
      if (results.length > 0) {
        results.map(item => {
          let matchResultsItem = {};
          let origenalResultItem = {};
          origenalResultItem.errorMsg = "";
          matchInfo.map(matchInfoItem => {
            if (item[matchInfoItem.label]) {
              matchResultsItem[matchInfoItem.value] = item[matchInfoItem.label];
              origenalResultItem[matchInfoItem.value] =
                item[matchInfoItem.label];
            } else {
              matchResultsItem[matchInfoItem.value] = "";
              origenalResultItem[matchInfoItem.value] = "";
            }
            if (matchInfoItem.value == "vip") {
              matchResultsItem.vip = this.watchVip(matchResultsItem.vip);
            }
          });
          matchResults.push(matchResultsItem);
          origenalResult.push(origenalResultItem);
        });
      }
      origenalResult = _this.checkTableData(
        _this,
        matchResults,
        origenalResult
      );
      //   console.info("_this.checkTableDataLock--"+_this.checkTableDataLock)
      if (_this.checkTableDataLock == false) {
        _this.memberData = origenalResult;
      } else {
        _this.dialogNum = matchResults.length;
        _this.centerDialogVisible= true;
        this.firstSheetName = firstSheetName;
        this.daoruData = matchResults;
        this.daoruType = true;
      }

      console.log(
        "获取的导入结果matchResults--" + JSON.stringify(matchResults)
      );
      console.log(
        "获取的导入结果origenalResult--" + JSON.stringify(origenalResult)
      );

      // console.log("获取的表头信息header--" + header)
      // console.log("获取的表头信息firstSheetName--" + firstSheetName)

    },

    //表格数据校验
    checkTableData(_this, data, origenalData) {
      let errorTableDate = [];
      let mobileList = []
      if (data.length > 0) {
        data.map((item, index) => {
          let lock = false;
          if (item.companyId == "") {
            lock = true;
            origenalData[index].errorMsg += "企业id不能为空，";
          } else if (item.companyId != _this.companyForm.id) {
            lock = true;
            origenalData[index].errorMsg += "企业id输入有误，";
          }
          if (item.companyName == "") {
            lock = true;
            origenalData[index].errorMsg += "企业名称不能为空，";
          } else if (item.companyName != _this.companyForm.name) {
            lock = true;
            origenalData[index].errorMsg += "企业名称输入有误，";
          }
          if (item.mobile == "") {
            lock = true;
            origenalData[index].errorMsg += "手机号码不能为空，";
          } else if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(item.mobile)) {
            lock = true;
            origenalData[index].errorMsg += "手机号码输入有误，";
          }else if(mobileList.indexOf(item.mobile) > -1 ){
                lock = true;
                origenalData[index].errorMsg += "手机号码存在重复，";
            }else if(mobileList.indexOf(item.mobile)  == -1 ){
                mobileList.push(item.mobile)
            }
          if (item.name == "") {
            lock = true;
            origenalData[index].errorMsg += "用户名字不能为空，";
          }
          if (item.vip == -1) {
            lock = true;
            origenalData[index].errorMsg += "vip等级输入有误，";
          }
          if (lock) {
            _this.checkTableDataLock = false;
            errorTableDate.push(origenalData[index]);
          }
        });
        if (errorTableDate.length == 0) {
          _this.checkTableDataLock = true;
        }else if(errorTableDate.length > 0){
            errorTableDate.map((item)=>{
                item.errorMsg = item.errorMsg.substr(0, item.errorMsg.length-1)
            })
        }
      }
      return errorTableDate;
    },

    daoruClick() {
      this.$refs.upload.handleUpload();
    },

    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 266; //减去页面上固定高度height
          } else {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 220; //减去页面上固定高度height
          }
        })();
      };
    },

    comeIn() {
      console.log("222");
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - 220; //减去页面上固定高度height
    },

    //查询企业的信息，员工数、企业余额、企业福利金余额
    companyInfo() {
      var _this = this;
      _this.companyForm.id = this.$route.query.id;
      find(this.$route.query.id)
        .then(response => {
          console.log("请求返回的数据" + JSON.stringify(response));
          if (response.type == "success") {
            _this.companyForm.id = response.data.id;
            _this.companyForm.name = response.data.name;
            _this.companyForm.num = response.data.num;
            _this.companyForm.balance = response.data.balance;
            _this.companyForm.welfare = response.data.welfare;
          } else {
            _this.$message({
              message: response.content,
              offset: 120,
              center: true
            });
          }
        })
        .catch(error => {});
    },

    //查询企业员工的信息
    loadMember(val) {
      console.log("传输过来的企业id" + val);
      var _this = this;
      let params = new URLSearchParams();
      params.append("pageNum", _this.pageNum);
      params.append("pageSize", _this.pageSize);
      params.append("phone", _this.keyword.phone);
      params.append("name", _this.keyword.name);
      params.append("vip", _this.keyword.vip);
      params.append("memberCategoryId", _this.memberCategoryId);
      params.append("deleted", _this.deleted);
      list(params)
        .then(response => {
          // console.log("请求的会员信息"+JSON.stringify(response) )
          _this.memberData = response.data.data;
          _this.total = response.data.total;
        })
        .catch(error => {
          console.log("error!!");
        });
    },

    chooseClick() {
      this.queryType = !this.queryType;
      if (this.queryType == false) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 266; //减去页面上固定高度height
      } else {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220; //减去页面上固定高度height
      }
    },

    deleteMember(data) {
      console.log(data);
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(data.id)
            .then(response => {
              console.log(response);
              _this.memberData.forEach(function(item, index) {
                if (item.id == data.id) {
                  _this.memberData.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            })
            .catch(error => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },

    //确认上传的服务器请求事件
    updateClick() {
      let _this = this;
      if (this.checkTableDataLock) {
        this.popoverVisible = false;
        this.checked = true;

        console.info("发送服务器的请求被调用了this.companyForm.id--"+this.companyForm.id);
        console.info("发送服务器的请求被调用了this.daoruData--"+JSON.stringify(this.daoruData));
        let idInfo = {companyId:this.companyForm.id}
        upload(idInfo, this.daoruData)
          .then(response => {
                this.checked = false;
                if(response.data.returnCode == "success"){
                    console.log("名单导入的回复信息"+JSON.stringify(response) )
                    EventBus.$emit("employee-add",this.companyForm)
                    _this.$store.dispatch("tagsView/delView", _this.$route).then(({ visitedViews }) => {
                    _this.$router.push({
                    path: "/company/employeeList",
                    query: { id: _this.companyForm.id }
                    });
                    }); // 关闭当前tab回到列表
                    _this.$message({
                    message: response.content,
                    offset: 120,
                    center: true
                    });
                }else if(response.data.returnCode == "error"){
                    console.log("名单导入的回复信息"+JSON.stringify(response) )
                    this.checkTableDataLock = false
                    if(response.data.vo.length > 0){
                        response.data.vo.map((item)=>{
                            item.vip = this.matchVip(item.vip)
                            item.errorMsg = item.result
                        })
                    }
                    _this.memberData = response.data.vo
                }

          })
          .catch(error => {
            console.log("error!!");
            this.checked = false;
          });
      }else{
         _this.$message({
                    message: "请先修正导入表格，再重新导入",
                    offset: 120,
                    center: true
                    });
      }

      this.query.phone = "";
      this.query.name = "";
      this.query.vip = "";
      this.keyword = this.query;
      this.pageNum = 1;
      // this.loadMember()
    }
  }
};
</script>

<style scoped>
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #f2f2f2;
}
#DialogMsg{
      color: crimson;
  }
</style>
